package com.chaihu.api.listener.admin.menu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chaihu.api.listener.AbstractServiceApiListener;
import com.chaihu.bean.enums.MsgCode;
import com.chaihu.bean.in.admin.menu.QueryMenusIn;
import com.chaihu.bean.in.user.userinfo.QueryUserIn;
import com.chaihu.bean.out.admin.menu.QueryMenusOut;
import com.chaihu.bean.out.user.userinfo.QueryUserOut;
import com.chaihu.bean.result.ResponseResult;
import com.chaihu.core.annotation.ChaihuListener;
import com.chaihu.core.context.DataFlowContext;
import com.chaihu.core.event.service.api.ServiceDataFlowEvent;
import com.chaihu.intf.admin.menu.QueryMenusService;
import com.chaihu.intf.user.QueryUsersService;
import com.chaihu.utils.constant.ServiceCodeConstant;
import com.chaihu.utils.util.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author chaihu
 * @date 2021/10/13
 */
@Slf4j
@ChaihuListener("queryMenusListener")
public class QueryMenusListener extends AbstractServiceApiListener {

    @Autowired
    private QueryMenusService queryMenusService;
    @Autowired
    private QueryUsersService queryUsersService;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        log.info("========= json 入参：{}", reqJson.toJSONString());

        Assert.hasKeyAndValue(reqJson,"userId", MsgCode.SUCCESS.getMsg());
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        String userId = reqJson.getString("userId");
        String levelCd = queryLevelCd(userId);
        if (StringUtils.isEmpty(levelCd)) {
            ResponseResult responseResult = new ResponseResult(MsgCode.ERROR.getCode(), "未查询到用户级别");
            ResponseEntity<String> responseEntity = new ResponseEntity<>(JSONObject.toJSONString(responseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }

        QueryMenusIn queryMenusIn = new QueryMenusIn();
        queryMenusIn.setDomain(levelCd);
        queryMenusIn.setUserId(userId);
        ResponseResult<List<QueryMenusOut>> queryMenusOutResponseResult = queryMenusService.queryMenus(queryMenusIn);
        if (!StringUtils.equals(MsgCode.SUCCESS.getCode(), queryMenusOutResponseResult.getCode()) || CollectionUtils.isEmpty(queryMenusOutResponseResult.getData())) {
            ResponseEntity<String> responseEntity = new ResponseEntity<>(JSONObject.toJSONString(queryMenusOutResponseResult), HttpStatus.OK);
            context.setResponseEntity(responseEntity);
            return;
        }
        List<QueryMenusOut> queryMenusOutList = queryMenusOutResponseResult.getData();
        JSONArray tempMenus = refreshMenusInfo(queryMenusOutList);

        ResponseEntity<String> responseEntity = new ResponseEntity<>(tempMenus.toJSONString(), HttpStatus.OK);
        context.setResponseEntity(responseEntity);
    }

    /**
     * 根据用户ID查询类型信息
     *
     * @param userId
     * @return
     */
    private String queryLevelCd(String userId) {
        QueryUserIn queryUserIn = new QueryUserIn();
        queryUserIn.setUserId(userId);
        ResponseResult<List<QueryUserOut>> queryUsersResponseResult = queryUsersService.queryUsers(queryUserIn);
        if (!StringUtils.equals(MsgCode.SUCCESS.getCode(), queryUsersResponseResult.getCode()) || CollectionUtils.isEmpty(queryUsersResponseResult.getData())) {
            return null;
        }
        QueryUserOut queryUserOut = queryUsersResponseResult.getData().get(0);
        return queryUserOut.getLevelCd();
    }

    /**
     * 刷新菜单信息
     * 将 数据 [{
     * "gId": "800201904001",
     * "menuDescription": "添加员工",
     * "menuGroupSeq": 1,
     * "menuSeq": 1,
     * "icon": "fa-desktop",
     * "mId": "700201904001",
     * "menuName": "添加员工",
     * "pId": "500201904001",
     * "menuGroupName": "员工管理",
     * "label": "",
     * "menuGroupDescription": "员工管理",
     * "url": "/"
     * }],
     * 转为：
     * "[{'id':1,'icon':'fa-desktop','name':'我的菜单','label':'HOT','childs':[" +
     * "{'name':'子菜单','href':'http://www.baidu.com'}]}," +
     * "{'id':2,'icon':'fa-flask','name':'我的菜单','childs':[],'href':'/doc'}," +
     * "{'id':3,'icon':'fa-globe','name':'我的菜单','childs':[{'name':'子菜单','href':'http://www.baidu.com'}]}" +
     * "]";
     *
     * @param queryMenusOutList 菜单列表
     * @return
     */
    private JSONArray refreshMenusInfo(List<QueryMenusOut> queryMenusOutList) {
        JSONArray tempMenus = new JSONArray();
        JSONObject tempMenu = null;
        for (int menuIndex = 0; menuIndex < queryMenusOutList.size(); menuIndex++) {
            QueryMenusOut queryMenusOut = queryMenusOutList.get(menuIndex);
            tempMenu = this.getMenuFromMenus(tempMenus, queryMenusOut.getgId());
            if (tempMenu == null) {
                tempMenu = new JSONObject();
                tempMenu.put("id", queryMenusOut.getgId());
                tempMenu.put("icon", queryMenusOut.getIcon());
                tempMenu.put("name", queryMenusOut.getMenuGroupName());
                tempMenu.put("label", queryMenusOut.getLabel());
                tempMenu.put("seq", queryMenusOut.getMenuGroupSeq());
                tempMenu.put("childs", new JSONArray());
                tempMenus.add(tempMenu);
            }
            //获取孩子菜单
            JSONArray childs = tempMenu.getJSONArray("childs");
            JSONObject childMenu = new JSONObject();
            childMenu.put("name", queryMenusOut.getMenuName());
            childMenu.put("href", queryMenusOut.getUrl());
            childMenu.put("seq", queryMenusOut.getMenuSeq());
            childMenu.put("isShow", queryMenusOut.getIsShow());
            childs.add(childMenu);
        }
        return tempMenus;
    }

    /**
     * 在菜单列表查询菜单
     *
     * @param gId
     * @return
     */
    private JSONObject getMenuFromMenus(JSONArray tempMenus, String gId) {
        for (int tempIndex = 0; tempIndex < tempMenus.size(); tempIndex++) {
            if (tempMenus.getJSONObject(tempIndex).getString("id").equals(gId)) {
                return tempMenus.getJSONObject(tempIndex);
            }
        }

        return null;
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeConstant.SERVICE_CODE_ADMIN_QUERY_MENU_INFO;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.GET;
    }
}
